{% extends "base.html" %}

{% block title %}图书管理系统 - 首页{% endblock %}

{% block content %}
<div class="container mt-4">
    <!-- Redis访问计数器 -->


    <!-- 搜索和筛选区域 -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="input-group">
                <input type="text" id="search-input" class="form-control" placeholder="搜索书名、作者或ISBN...">
                <button class="btn btn-primary" id="search-btn">
                    <i class="fas fa-search"></i> 搜索
                </button>
            </div>
        </div>
        <div class="col-md-6 text-end">
            <div class="dropdown">
                <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="filterDropdown" data-bs-toggle="dropdown">
                    <i class="fas fa-filter"></i> 筛选条件
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <li><a class="dropdown-item filter-option" href="#" data-status="all">全部书籍</a></li>
                    <li><a class="dropdown-item filter-option" href="#" data-status="available">可借阅</a></li>
                    <li><a class="dropdown-item filter-option" href="#" data-status="borrowed">已借出</a></li>
                    <li><a class="dropdown-item filter-option" href="#" data-status="reserved">已预约</a></li>
                </ul>
            </div>
        </div>
    </div>

    <!-- 图书展示区域 -->
    <div class="row" id="book-list">
        <!-- 图书将通过JavaScript动态加载 -->
        <div class="col-12 text-center my-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
        </div>
    </div>

    <!-- 分页控件 -->
    <nav aria-label="Page navigation" class="mt-4">
        <ul class="pagination justify-content-center" id="pagination">
            <!-- 分页将通过JavaScript动态生成 -->
        </ul>
    </nav>
</div>

<!-- 申请借阅模态框 -->
<div class="modal fade" id="borrowModal" tabindex="-1" aria-labelledby="borrowModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="borrowModalLabel">申请借阅</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="borrowForm">
                    <div class="mb-3">
                        <label for="borrowName" class="form-label">姓名</label>
                        <input type="text" class="form-control" id="borrowName" required>
                    </div>
                    <div class="mb-3">
                        <label for="borrowTime" class="form-label">申请借阅时间</label>
                        <input type="datetime-local" class="form-control" id="borrowTime" required>
                    </div>
                    <div class="mb-3">
                        <label for="returnTime" class="form-label">归还时间</label>
                        <input type="datetime-local" class="form-control" id="returnTime" required>
                    </div>
                    <div class="mb-3">
                        <label for="borrowClass" class="form-label">所属班级</label>
                        <input type="text" class="form-control" id="borrowClass" required>
                    </div>
                    <div class="mb-3">
                        <label for="borrowStudentId" class="form-label">学号</label>
                        <input type="text" class="form-control" id="borrowStudentId" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-success" id="submitBorrowRequest">提交申请</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 初始化变量
    let currentPage = 1;
    const booksPerPage = 6;
    let allBooks = [];
    let filteredBooks = [];
    let currentFilter = 'all';

    // 获取DOM元素
    const bookList = document.getElementById('book-list');
    const pagination = document.getElementById('pagination');
    const searchInput = document.getElementById('search-input');
    const searchBtn = document.getElementById('search-btn');
    const borrowModal = new bootstrap.Modal(document.getElementById('borrowModal'));
    const submitBorrowRequest = document.getElementById('submitBorrowRequest');

    // 加载书籍数据
    function loadBooks() {
        bookList.innerHTML = `
            <div class="col-12 text-center my-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
            </div>`;

        fetch('/book/books')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                console.log('获取到的书籍数据:', data);

                if (!data || !data.success) {
                    throw new Error(data?.message || '获取书籍数据失败');
                }

                allBooks = data.data || [];
                console.log('处理后的书籍列表:', allBooks);

                applyFilter();
                renderBooks();
                renderPagination();
            })
            .catch(error => {
                console.error('加载书籍错误:', error);
                bookList.innerHTML = `
                    <div class="col-12 text-center text-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        ${error.message || '加载书籍失败，请刷新页面重试'}
                    </div>`;
            });
    }

    // 应用筛选条件
    function applyFilter() {
        if (currentFilter === 'all') {
            filteredBooks = [...allBooks];
        } else {
            filteredBooks = allBooks.filter(book => {
                const status = book.status || (book.available ? 'available' : 'borrowed');
                return status === currentFilter;
            });
        }
    }

    // 渲染书籍列表
    function renderBooks() {
        const startIndex = (currentPage - 1) * booksPerPage;
        const endIndex = startIndex + booksPerPage;
        const booksToShow = filteredBooks.slice(startIndex, endIndex);

        if (booksToShow.length === 0) {
            bookList.innerHTML = '<div class="col-12 text-center">没有找到符合条件的书籍</div>';
            return;
        }

        let html = '';
        booksToShow.forEach(book => {
            const status = book.status || (book.available ? 'available' : 'borrowed');
            let statusClass, statusText;

            switch(status) {
                case 'available':
                    statusClass = 'success';
                    statusText = '可借阅';
                    break;
                case 'borrowed':
                    statusClass = 'danger';
                    statusText = '已借出';
                    break;
                case 'reserved':
                    statusClass = 'warning';
                    statusText = '已预约';
                    break;
                default:
                    statusClass = 'secondary';
                    statusText = '未知状态';
            }

            html += `
            <div class="col-md-4 mb-4">
                <div class="card h-100 shadow-sm">
                    <div class="card-header bg-light">
                        <h5 class="card-title mb-0">${book.title || '未知书名'}</h5>
                    </div>
                    <div class="card-body">
                        <p class="card-text text-muted">
                            <i class="fas fa-user-edit"></i> ${book.author || '未知作者'}
                        </p>
                        <p class="card-text">
                            <small class="text-muted">
                                <i class="fas fa-bookmark"></i> ${book.category || '未分类'}
                            </small>
                        </p>
                        <p class="card-text">
                            <small class="text-muted">
                                <i class="fas fa-barcode"></i> ${book.isbn || '无ISBN'}
                            </small>
                        </p>
                        <div class="d-flex justify-content-between align-items-center mt-3">
                            <span class="badge bg-${statusClass}">${statusText}</span>
                            <div class="btn-group">
                                <a href="/book/books/${book.id}" class="btn btn-sm btn-outline-primary">查看详情</a>
                                <button class="btn btn-sm btn-outline-success ${status === 'available' ? '' : 'disabled'}"
                                        data-id="${book.id}">
                                    申请借阅
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>`;
        });

        bookList.innerHTML = html;

        // 申请借阅按钮点击事件
        document.querySelectorAll('.btn-outline-success').forEach(btn => {
            btn.addEventListener('click', function(e) {
                const bookId = this.dataset.id;
                document.getElementById('submitBorrowRequest').dataset.bookId = bookId;
                borrowModal.show();
            });
        });
    }

    // 提交借阅请求
submitBorrowRequest.addEventListener('click', function() {
    const bookId = this.dataset.bookId;
    const formData = {
        name: document.getElementById('borrowName').value,
        borrowTime: document.getElementById('borrowTime').value,
        returnTime: document.getElementById('returnTime').value,
        className: document.getElementById('borrowClass').value,
        studentId: document.getElementById('borrowStudentId').value,
        bookId: bookId
    };

    // 验证表单
    if (!formData.name || !formData.borrowTime || !formData.returnTime ||
        !formData.className || !formData.studentId) {
        alert('请填写所有必填字段');
        return;
    }

    // 发送借阅请求
    fetch('/book/borrow', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('借阅申请已提交，等待管理员审核');
            document.getElementById('borrowForm').reset();
            borrowModal.hide();
        } else {
            alert(data.message || '提交申请失败');
        }
    })
    .catch(error => {
        console.error('提交申请错误:', error);
        alert('提交申请失败，请重试');
    });
});


    // 渲染分页控件
    function renderPagination() {
        const totalPages = Math.ceil(filteredBooks.length / booksPerPage);

        if (totalPages <= 1) {
            pagination.innerHTML = '';
            return;
        }

        let html = '';

        // 上一页按钮
        html += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a>
        </li>`;

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            html += `<li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" data-page="${i}">${i}</a>
            </li>`;
        }

        // 下一页按钮
        html += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a>
        </li>`;

        pagination.innerHTML = html;
    }

    // 事件监听器
    pagination.addEventListener('click', function(e) {
        e.preventDefault();
        if (e.target.tagName === 'A') {
            currentPage = parseInt(e.target.dataset.page);
            renderBooks();
            renderPagination();
            window.scrollTo({top: 0, behavior: 'smooth'});
        }
    });

    // 筛选条件点击事件
    document.querySelectorAll('.filter-option').forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            currentFilter = this.dataset.status;
            currentPage = 1;
            applyFilter();
            renderBooks();
            renderPagination();
        });
    });

    // 搜索功能
    searchBtn.addEventListener('click', function() {
        const searchTerm = searchInput.value.trim().toLowerCase();

        if (searchTerm) {
            filteredBooks = allBooks.filter(book =>
                (book.title && book.title.toLowerCase().includes(searchTerm)) ||
                (book.author && book.author.toLowerCase().includes(searchTerm)) ||
                (book.isbn && book.isbn.includes(searchTerm))
            );
        } else {
            applyFilter();
        }

        currentPage = 1;
        renderBooks();
        renderPagination();
    });

    // 回车键触发搜索
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchBtn.click();
        }
    });

    // 初始加载
    loadBooks();
});
</script>

<style>
    /* 图书卡片样式 */
    .book-card {
        transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        border: none;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        margin-bottom: 1.5rem;
        height: 100%;
        display: flex;
        flex-direction: column;
    }

    .book-card:hover {
        transform: translateY(-8px);
        box-shadow: 0 15px 30px rgba(0,0,0,0.1);
    }

    .book-card-img {
        height: 200px;
        object-fit: cover;
        border-bottom: 1px solid rgba(0,0,0,0.05);
    }

    .book-card-body {
        padding: 1.5rem;
        flex-grow: 1;
        display: flex;
        flex-direction: column;
    }

    .book-card-title {
        font-weight: 600;
        margin-bottom: 0.75rem;
        color: var(--dark-color);
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .book-card-text {
        color: #6c757d;
        margin-bottom: 1rem;
        flex-grow: 1;
    }

    .book-card-footer {
        background-color: transparent;
        border-top: none;
        padding: 0 1.5rem 1.5rem;
    }

    /* 搜索和筛选区域 */
    .search-filter-container {
        background-color: white;
        border-radius: 16px;
        padding: 1.5rem;
        box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        margin-bottom: 2rem;
    }

    .search-input {
        border-radius: 12px;
        padding: 0.75rem 1.25rem;
        border: 1px solid rgba(0,0,0,0.1);
        transition: all 0.3s ease;
    }

    .search-input:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.25rem rgba(67, 97, 238, 0.25);
    }

    .filter-btn {
        border-radius: 12px;
        padding: 0.5rem 1rem;
        font-weight: 500;
        transition: all 0.2s ease;
    }

    .filter-btn.active {
        background-color: var(--primary-color);
        color: white;
    }

    /* 分页样式 */
    .page-item.active .page-link {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
    }

    .page-link {
        color: var(--primary-color);
        border-radius: 12px;
        margin: 0 0.25rem;
        padding: 0.5rem 1rem;
        transition: all 0.2s ease;
    }

    .page-link:hover {
        color: var(--accent-color);
    }

    /* 加载动画 */
    .loading-spinner {
        display: inline-block;
        width: 2rem;
        height: 2rem;
        border: 0.25em solid rgba(67, 97, 238, 0.2);
        border-radius: 50%;
        border-top-color: var(--primary-color);
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        to { transform: rotate(360deg); }
    }

    /* 响应式调整 */
    @media (max-width: 768px) {
        .book-card-img {
            height: 160px;
        }
        
        .search-filter-container {
            padding: 1rem;
        }
    }
</style>
{% endblock %}
